package com.shuimutong.gutil.http.okhttp;

import okhttp3.*;

import java.io.IOException;

public class HttpRequest {
    private static volatile OkHttpClient OK_HTTP_CLIENT;
    private final static Object LOCK = new Object();
    public final static MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");

    private static OkHttpClient getClient() {
        if(OK_HTTP_CLIENT == null) {
            synchronized (LOCK) {
                if (OK_HTTP_CLIENT == null) {
                    OK_HTTP_CLIENT = new OkHttpClient();
                }
            }
        }
        return OK_HTTP_CLIENT;
    }

    public static String get(String url) throws IOException {
        Request req = new Request.Builder()
                .url(url)
                .build();
        try(Response res = getClient().newCall(req).execute()) {
            return res.body().string();
        }
    }

    public static String post(String url, String jsonBody) throws IOException {
        RequestBody body = RequestBody.create(JSON_TYPE, jsonBody);
        Request req = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try(Response res = getClient().newCall(req).execute()) {
            return res.body().string();
        }
    }
}
